﻿using System;
using System.Windows.Forms;
using Group_Mail.Controls;
using mshtml;

namespace Group_Mail
{
    public partial class frmMessageCreator : Form
    {
        private CheckBoxToolStripItem chkAutoPlainText;
        private IHTMLDocument2 document;
        private bool saveClose;

        public frmMessageCreator()
        {
            InitializeComponent();
        }

        public frmMessageCreator(Message message) : this()
        {
            Message = message;
        }

        public Message Message { get; private set; }

        private void frmMessageCreator_Load(object sender, EventArgs e)
        {
            ddlAccounts.DataSource = Manager.Accounts;
            ddlAccounts.DisplayMember = "Name";
            ddlAccounts.ValueMember = "Id";

            ddlGroups.DataSource = Manager.Groups;
            ddlGroups.DisplayMember = "Value";
            ddlGroups.ValueMember = "Key";

            ddlGroups_SelectionChangeCommitted(ddlGroups, EventArgs.Empty);

            foreach (var entry in Manager.Templates)
            {
                var item = new ToolStripMenuItem(entry.Value) {Tag = entry.Key};
                item.Click += TemplateItem_Click;
                btnTemplates.DropDownItems.Add(item);
            }

            webBrowser.DocumentText = "<html><body></body></html>";
            document = webBrowser.Document.DomDocument as IHTMLDocument2;
            document.designMode = "On";
            webBrowser.Document.ContextMenuShowing += Document_ContextMenuShowing;

            chkAutoPlainText = new CheckBoxToolStripItem {Text = "Auto Plaint Text", Checked = true};
            toolStrip.Items.Insert(4, chkAutoPlainText);

            if (Message != null)
            {
                ddlAccounts.SelectedValue = Message.AccountId;
                ddlGroups.SelectedItem = Message.GroupId;
                txtSubject.Text = Message.Subject;
                webBrowser.Document.Body.InnerHtml = Message.HtmlBody;
                txtPlaintText.Text = Message.TextBody;
                chkAutoPlainText.Checked = Message.AutoPlainText;
            }
        }

        private void TemplateItem_Click(object sender, EventArgs e)
        {
            var id = ((ToolStripMenuItem) sender).Tag.ToString();
            var template = Manager.GetTemplateById(id);

            if (MessageBox.Show("Do you want replace current message by this template?", "Group Mail",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                webBrowser.Document.Body.InnerHtml = template.HtmlBody;
            }
        }

        private static void Document_ContextMenuShowing(object sender, HtmlElementEventArgs e)
        {
            e.ReturnValue = false;
        }

        private void ddlGroups_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (ddlGroups.SelectedItem != null)
            {
                btnFields.DropDownItems.Clear();

                var item = (KeyValuePairOfString) ddlGroups.SelectedItem;
                var group = Manager.GetGroupById(item.Key);
                foreach (var field in group.Fields)
                {
                    var ddlItem = new ToolStripMenuItem(field.Name);
                    ddlItem.Click += ddlItem_Click;
                    btnFields.DropDownItems.Add(ddlItem);
                }
            }
        }

        private void ddlItem_Click(object sender, EventArgs e)
        {
            var item = sender as ToolStripMenuItem;
            var range = document.selection.createRange() as IHTMLTxtRange;
            range.pasteHTML(string.Format("${0}$", item.Text));
            range.collapse(false);
            range.select();
        }

        private void btnSwitchMode_Click(object sender, EventArgs e)
        {
            if (btnSwitchMode.Tag.ToString() == "Html")
            {
                btnSwitchMode.Text = "Plain Text";
                btnSwitchMode.Tag = "Plain";
                wizardControl.SelectedIndex = 1;
            }
            else
            {
                btnSwitchMode.Text = "Html Text";
                btnSwitchMode.Tag = "Html";
                wizardControl.SelectedIndex = 0;
            }
        }

        private void btnFields_ButtonClick(object sender, EventArgs e)
        {
            btnFields.ShowDropDown();
        }

        private void btnTemplates_ButtonClick(object sender, EventArgs e)
        {
            btnTemplates.ShowDropDown();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            btnSend.ShowDropDown();
        }

        private bool Send()
        {
            if (ddlAccounts.SelectedItem == null)
            {
                MessageBox.Show("Please enter your account to send message", "Group Mail",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (ddlGroups.SelectedItem == null)
            {
                MessageBox.Show("Please enter group to send message", "Group Mail",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (string.IsNullOrEmpty(txtSubject.Text.Trim()))
            {
                MessageBox.Show("Please enter subject to send message", "Group Mail",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Message == null)
            {
                Message = new Message();
            }

            Message.AccountId = (ddlAccounts.SelectedItem as Account).Id;
            Message.GroupId = ((KeyValuePairOfString) ddlGroups.SelectedItem).Key;
            Message.Subject = txtSubject.Text.Trim();
            Message.AutoPlainText = chkAutoPlainText.Checked;
            Message.HtmlBody = webBrowser.Document.Body.InnerHtml ?? string.Empty;
            Message.TextBody = txtPlaintText.Text;

            if (string.IsNullOrEmpty(Message.Id))
            {
                Message.Id = Guid.NewGuid().ToString();
            }

            DialogResult = DialogResult.OK;
            return true;
        }

        private void frmMessageCreator_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!saveClose)
            {
                var result = MessageBox.Show("Do you want to save the message as draft?", "Group Mail",
                                             MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                switch (result)
                {
                    case DialogResult.Yes:
                        e.Cancel = !Send();
                        Message.Status = MessageStatus.Draft;
                        break;
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;
                }
            }
        }

        private void btnSaveDraft_Click(object sender, EventArgs e)
        {
            if (Send())
            {
                Message.Status = MessageStatus.Draft;
                saveClose = true;
                Close();
            }
        }

        private void btnSendWithoutDraft_Click(object sender, EventArgs e)
        {
            if (Send())
            {
                Message.Status = MessageStatus.Sending;
                saveClose = true;
                Close();
            }
        }
    }
}